﻿// Copyright (c) JosephZheng. All rights reserved. See License.txt in the project root for license

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;

namespace Lyra.Cache.Server.Interface
{
    public class GZip
    {
        public static byte[] Compress(byte[] data)
        {
            MemoryStream result = new MemoryStream();
            GZipStream zs = null;
            try
            {
                zs = new GZipStream(result, CompressionMode.Compress);
                zs.Write(data, 0, data.Length);
                zs.Flush();
                zs.Close();
                return result.ToArray();
            }
            catch (Exception ex) { throw ex; }
            finally
            {
                if (zs != null) zs.Close(); zs.Dispose();
                if (result != null) result.Close(); result.Dispose();
            }

            throw new NotImplementedException();
        }

        public static byte[] Decompress(byte[] data)
        {
            MemoryStream ms = new MemoryStream(data);
            ms.Position = 0;
            MemoryStream result = new MemoryStream();
            GZipStream zs = null;
            try
            {
                zs = new GZipStream(ms, CompressionMode.Decompress);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = zs.Read(buffer, 0, 1024)) > 0)
                {
                    result.Write(buffer, 0, len);
                }
                return result.ToArray();
            }
            catch (Exception ex) { throw ex; }
            finally
            {
                if (zs != null) zs.Close(); zs.Dispose();
                if (ms != null) ms.Close(); ms.Dispose();
                if (result != null) result.Close(); result.Dispose();
            }
        }
    }
}
